<?php
// 检查 MIMA cookie 是否存在且值为 "PHQH123456"
// if (!isset($_COOKIE['MIMA']) || $_COOKIE['MIMA'] !== 'PHQH123456') {
//     // 如果验证失败，重定向回登录页面
//     header('Location: index.html');
//     exit();
// }

$Uname = $_COOKIE['NAME'] ?? '';
$enorg = $_COOKIE['enorg'] ?? '';
// 配置和全局变量
date_default_timezone_set('UTC');
$today = new DateTime();
$date_folder = $today->format('Ymd');
$default_download_path = __DIR__ . '/downloads/' . $date_folder;

// 确保下载目录存在
if (!is_dir($default_download_path)) {
    mkdir($default_download_path, 0777, true);
}

// 加载API Keys
function load_api_keys() {
    $keys = [];
    $key_file_path = __DIR__ . '/'.$_COOKIE['enorg']. '_key.env';
    
    if (!file_exists($key_file_path)) {
        error_log("警告: API key文件不存在 - " . $key_file_path);
        return $keys;
    }
    
    try {
        $lines = file($key_file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $line = trim($line);
            if ($line && !str_starts_with($line, '#')) {
                $keys[] = $line;
            }
        }
        error_log("成功加载 " . count($keys) . " 个API keys");
        return $keys;
    } catch (Exception $e) {
        error_log("读取API key文件错误: " . $e->getMessage());
        return $keys;
    }
}

// 保存API Key到文件
function save_key_to_file($new_key) {
    $key_file_path = __DIR__ . '/'.$_COOKIE['enorg']. '_key.env';
    $existing_keys = [];
    $comments = [];
    
    if (file_exists($key_file_path)) {
        try {
            $lines = file($key_file_path, FILE_IGNORE_NEW_LINES);
            foreach ($lines as $line) {
                $trimmed = trim($line);
                if ($trimmed === '' || str_starts_with($trimmed, '#')) {
                    $comments[] = $line;
                } else {
                    $existing_keys[] = $trimmed;
                }
            }
        } catch (Exception $e) {
            error_log("读取现有key文件错误: " . $e->getMessage());
        }
    }
    
    // 去重检查
    if (in_array($new_key, $existing_keys)) {
        error_log("API key已存在，跳过添加");
        return;
    }
    
    $existing_keys[] = $new_key;
    sort($existing_keys);
    
    try {
        $file = fopen($key_file_path, 'w');
        foreach ($comments as $comment) {
            fwrite($file, $comment . "\n");
        }
        foreach ($existing_keys as $key) {
            fwrite($file, $key . "\n");
        }
        fclose($file);
        error_log("成功将新API key添加到文件中");
    } catch (Exception $e) {
        error_log("保存API key到文件错误: " . $e->getMessage());
    }
}

// 获取下一个API Key
function get_next_api_key($custom_key = null) {
    static $current_key_index = 0;
    static $submission_count = 0;
    
    $submission_count++;
    error_log("第 " . $submission_count . " 次提交");
    
    // 优先使用自定义key
    if (!empty($custom_key)) {
        $custom_key = trim($custom_key);
        if ($custom_key) {
            error_log("使用自定义输入的API key");
            save_key_to_file($custom_key);
            return $custom_key;
        }
    }
    
    // 其次使用环境变量
    $env_key = getenv('ORAPI');
    if (!empty($env_key)) {
        $env_key = trim($env_key);
        if ($env_key) {
            error_log("使用环境变量ORAPI中的API key");
            return $env_key;
        }
    }
    
    // 最后使用文件中的keys
    $api_keys = load_api_keys();
    if (empty($api_keys)) {
        throw new Exception("没有可用的API key：请输入自定义key、设置ORAPI环境变量或在env文件中添加keys");
    }
    
    $selected_key = $api_keys[$current_key_index % count($api_keys)];
    error_log("使用文件中第 " . ($current_key_index + 1) . " 个API key（共 " . count($api_keys) . " 个）");
    
    $current_key_index = ($current_key_index + 1) % count($api_keys);
    return $selected_key;
}

// 百度翻译功能
function baidu_translate($query, $from_lang = 'zh', $to_lang = 'en') {
    $appid = '20230502001663178';
    $appkey = 'Dz2_wutD286PSys6hHLa';
    
    // 如果是英文，直接返回
    if ($from_lang == 'en' || ($from_lang == 'auto' && ctype_alnum(str_replace(' ', '', $query)))) {
        return $query;
    }
    
    $endpoint = 'http://api.fanyi.baidu.com';
    $path = '/api/trans/vip/translate';
    $url = $endpoint . $path;
    
    $salt = rand(32768, 65536);
    $sign = md5($appid . $query . $salt . $appkey);
    
    $payload = [
        'appid' => $appid,
        'q' => $query,
        'from' => $from_lang,
        'to' => $to_lang,
        'salt' => $salt,
        'sign' => $sign
    ];
    
    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 将超时时间从100秒调整为30秒
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if (isset($result['trans_result']) && !empty($result['trans_result'])) {
            $translated = [];
            foreach ($result['trans_result'] as $item) {
                $translated[] = $item['dst'];
            }
            return implode(' ', $translated);
        } else {
            error_log("百度翻译API响应异常: " . json_encode($result));
            return $query;
        }
    } catch (Exception $e) {
        error_log("百度翻译失败: " . $e->getMessage());
        return $query;
    }
}

// 加载样式
function load_styles() {
    $styles = [];
    $styles_dict = [];
    $csv_path = __DIR__ . '/styles.csv';
    
    if (!file_exists($csv_path)) {
        error_log("警告: 样式文件不存在 - " . $csv_path);
        return [$styles, $styles_dict];
    }
    
    try {
        $file = fopen($csv_path, 'r');
        if ($file) {
            $header = fgetcsv($file);
            while (($row = fgetcsv($file)) !== false) {
                $name = trim($row[0] ?? '');
                $prompt = trim($row[1] ?? '');
                $negative_prompt = trim($row[2] ?? ''); // 新增：处理negative_prompt
                $remark = trim($row[3] ?? ''); // 修正：remark是第4列
                
                if ($name) {
                    $styles[] = $name;
                    $styles_dict[$name] = [
                        'prompt' => $prompt,
                        'negative_prompt' => $negative_prompt,
                        'remark' => $remark
                    ];
                }
            }
            fclose($file);
        }
        return [$styles, $styles_dict];
    } catch (Exception $e) {
        error_log("读取样式文件错误: " . $e->getMessage());
        return [$styles, $styles_dict];
    }
}

// 提取图片URL
function extract_image_url($remark) {
    if (empty($remark)) {
        return null;
    }
    
    $url_pattern = '/http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+/';
    preg_match($url_pattern, $remark, $matches);
    
    return $matches[0] ?? null;
}

// 查询API Key使用情况
function query_api_key_usage($custom_key = null) {
    try {
        $query_key = null;
        $key_source = "";
        
        if (!empty($custom_key)) {
            $query_key = trim($custom_key);
            $key_source = "自定义输入";
            save_key_to_file($query_key);
        } else {
            $env_key = getenv('ORAPI');
            if (!empty($env_key)) {
                $query_key = trim($env_key);
                $key_source = "环境变量ORAPI";
            } else {
                $api_keys = load_api_keys();
                if (!empty($api_keys)) {
                    $query_key = $api_keys[0];
                    $key_source = "文件中第1个key（共" . count($api_keys) . "个）";
                }
            }
        }
        
        if (empty($query_key)) {
            return "错误: 没有可用的API Key进行查询\n请输入自定义key、设置ORAPI环境变量或在env文件中添加keys";
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://openrouter.ai/api/v1/key");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer " . $query_key,
            "Content-Type: application/json"
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($http_code != 200) {
            return "API请求错误 (HTTP $http_code): " . $response;
        }
        
        $result = json_decode($response, true);
        
        if (isset($result['data'])) {
            $data = $result['data'];
            
            $info = [];
            $info[] = "=== API Key 使用情况 ===";
            $info[] = "查询的Key来源: " . $key_source;
            $info[] = "标签: " . ($data['label'] ?? 'N/A');
            $info[] = "已使用信用额度: " . ($data['usage'] ?? 0);
            
            $limit = $data['limit'] ?? null;
            if ($limit === null) {
                $info[] = "信用额度限制: 无限制";
            } else {
                $info[] = "信用额度限制: " . $limit;
                if ($limit > 0) {
                    $remaining = $limit - ($data['usage'] ?? 0);
                    $info[] = "剩余信用额度: " . $remaining;
                }
            }
            
            $is_free = $data['is_free_tier'] ?? false;
            $info[] = "免费账户: " . ($is_free ? '是' : '否');
            
            $info[] = "\n=== 原始响应数据 ===";
            $info[] = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            
            return implode("\n", $info);
        } else {
            return "API响应格式异常: " . json_encode($result, JSON_PRETTY_PRINT);
        }
    } catch (Exception $e) {
        return "查询API Key使用情况失败: " . $e->getMessage();
    }
}

// 生成图片
function generate_image($prompt, $images, $api_key, $save_path) {
    try {
        $openrouter_key = get_next_api_key($api_key);
        if (empty($openrouter_key)) {
            throw new Exception("没有可用的API Key");
        }
        
        // 翻译提示词
        $original_chinese_prompt = $prompt;
        $final_prompt = $prompt;
        
        // 检测中文并翻译
        if (!empty($prompt) && preg_match('/[\x{4e00}-\x{9fff}]/u', $prompt)) {
            $translated_prompt = baidu_translate($prompt, 'zh', 'en');
            error_log("中文提示词: " . $original_chinese_prompt);
            error_log("英文提示词: " . $translated_prompt);
            $final_prompt = $translated_prompt;
        } else {
            error_log("提示词: " . $prompt);
            $original_chinese_prompt = "";
        }
        
        $content = [["type" => "text", "text" => $final_prompt]];
        $cache_id = uniqid();
        $image_cache_paths = [];
        
        // 处理图片
foreach ($images as $i => $image_data) {
    if (!empty($image_data)) {
        // 判断是URL还是base64数据
        if (filter_var($image_data, FILTER_VALIDATE_URL)) {
            // URL图片
            $content[] = [
                "type" => "image_url",
                "image_url" => ["url" => $image_data]
            ];
            error_log("添加URL图片: " . $image_data);
        } else {
            // base64图片
            // 验证base64数据格式
            if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $matches)) {
                // 解码base64图片
                $image_base64 = base64_decode(str_replace(' ', '+', substr($image_data, strpos($image_data, ',') + 1)));
                
                // 生成缓存路径
                $image_cache_path = __DIR__ . "/downloads/{$cache_id}_{$i}.webp";
                
                // 创建一个临时文件来处理图像
                $temp_file = tempnam(sys_get_temp_dir(), 'img');
                file_put_contents($temp_file, $image_base64);

                // 根据原始格式创建图像资源
                $image_info = getimagesize($temp_file);
                $mime = $image_info['mime'];

                switch ($mime) {
                    case 'image/jpeg':
                        $source_image = imagecreatefromjpeg($temp_file);
                        break;
                    case 'image/png':
                        $source_image = imagecreatefrompng($temp_file);
                        // 启用 alpha 通道（透明度）
                        imagealphablending($source_image, false);
                        imagesavealpha($source_image, true);
                        break;
                    case 'image/gif':
                        $source_image = imagecreatefromgif($temp_file);
                        break;
                    default:
                        error_log("不支持的图片格式: " . $mime);
                        unlink($temp_file); // 删除临时文件
                        continue 2; // 跳出当前循环，继续下一个图片
                }

                // 获取原始图片的宽高
                $width = imagesx($source_image);
                $height = imagesy($source_image);

                // 创建一个新的真彩色图像
                $new_image = imagecreatetruecolor($width, $height);

                // 如果是 PNG 或 GIF，处理透明背景
                if ($mime === 'image/png' || $mime === 'image/gif') {
                    // 为新图像分配透明色
                    $transparent = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
                    imagefill($new_image, 0, 0, $transparent);
                    imagecolortransparent($new_image, $transparent);
                    // 保留 alpha 通道
                    imagealphablending($new_image, false);
                    imagesavealpha($new_image, true);
                }

                // 将源图像复制到新图像上
                imagecopy($new_image, $source_image, 0, 0, 0, 0, $width, $height);

                // 将新图像保存为 WebP 格式，质量设置为 95
                // 第三个参数是质量，范围 0-100，95 表示高质量
                $saved = imagewebp($new_image, $image_cache_path, 95);

                // 释放内存
                imagedestroy($source_image);
                imagedestroy($new_image);
                // 删除临时文件
                unlink($temp_file);

                if ($saved) {
                    $image_cache_paths[] = $image_cache_path;
                    
                    // 读取新生成的WebP文件并转换回base64，用于API请求
                    $webp_data = file_get_contents($image_cache_path);
                    $webp_base64 = 'data:image/webp;base64,' . base64_encode($webp_data);
                    
                    // 添加到请求内容 (使用新生成的base64数据)
                    $content[] = [
                        "type" => "image_url",
                        "image_url" => ["url" => $webp_base64]
                    ];
                    error_log("添加本地上传图片 (已转换为WebP 95%质量): " . $image_cache_path);
                } else {
                    error_log("无法将图片保存为WebP格式: " . $image_cache_path);
                    continue;
                }
            } else {
                error_log("无效的图片数据格式: " . substr($image_data, 0, 100) . "...");
                continue;
            }
        }
    }
}
        
        
        // 确保至少有一张有效图片
        if (count($content) <= 1) { // 只有文本内容，没有图片
            throw new Exception("至少需要一张有效图片");
        }
        
        // 准备API请求
        $data = [
            "model" => "google/gemini-2.5-flash-image-preview",
            "messages" => [["role" => "user", "content" => $content]],
            "temperature" => 0.7,
            "max_tokens" => 1000
        ];
        
        error_log("发送API请求，包含 " . (count($content) - 1) . " 张图片");
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://openrouter.ai/api/v1/chat/completions");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer " . $openrouter_key,
            "Content-Type: application/json",
            "HTTP-Referer: " . $_SERVER['HTTP_HOST'],
            "X-Title: BOZO - OpenRouter.ai"
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 将超时时间从600秒调整为300秒
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($http_code != 200) {
            throw new Exception("API请求错误 (HTTP $http_code): " . $response);
        }
        
        $result_data = json_decode($response, true);
        
        // 提取生成的图片
        if (isset($result_data['choices'][0]['message']['images'][0]['image_url']['url'])) {
            $image_url = $result_data['choices'][0]['message']['images'][0]['image_url']['url'];
            
            // 解码图片
            $image_parts = explode(";base64,", $image_url);
            $image_base64 = base64_decode($image_parts[1]);
            
            // 保存图片
            if (!empty($save_path) && is_dir($save_path)) {
                $timestamp = date('Ymd_His');
                $filename = "OR_{$timestamp}.png";
                $full_path = $save_path . '/' . $filename;
                file_put_contents($full_path, $image_base64);
                
                // 保存信息文件
                $txt_filename = "OR_{$timestamp}.txt";
                $txt_full_path = $save_path . '/' . $txt_filename;
                
                $txt_content = "=== 图片生成信息 ===\n\n";
                $txt_content .= "输入图片本地缓存路径：\n";
                if (!empty($image_cache_paths)) {
                    foreach ($image_cache_paths as $idx => $path) {
                        $txt_content .= "图片" . ($idx + 1) . ": " . realpath($path) . "\n";
                    }
                } else {
                    $txt_content .= "无输入图片缓存（使用URL图片）\n";
                }
                
                $txt_content .= "\n";
                if (!empty($original_chinese_prompt)) {
                    $txt_content .= "中文提示词：\n{$original_chinese_prompt}\n\n";
                    $txt_content .= "英文提示词：\n{$final_prompt}\n";
                } else {
                    $txt_content .= "提示词：\n{$final_prompt}\n";
                }
                
                file_put_contents($txt_full_path, $txt_content);
            }
            
            $log_detail = $result_data['choices'][0]['message']['content'] ?? '图片生成成功';
            if (!empty($original_chinese_prompt)) {
                $log_detail .= "\n恭喜您，图片已成功生成！\n\n输入的中文提示词：{$original_chinese_prompt}";
            } else {
                $log_detail .= "\n恭喜您，图片已成功生成！";
            }
            
            return [
                'success' => true,
                'image' => $image_url,
                'log' => $log_detail
            ];
        } else {
            throw new Exception("API未返回图片: " . json_encode($result_data));
        }
    } catch (Exception $e) {
        error_log("生成图片错误: " . $e->getMessage());
        return [
            'success' => false,
            'image' => null,
            'log' => "错误: " . $e->getMessage()
        ];
    }
}

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'load_styles':
            list($styles, $styles_dict) = load_styles();
            echo json_encode([
                'status' => 'success',
                'styles' => $styles,
                'styles_dict' => $styles_dict
            ]);
            exit;
            
        case 'preview_style':
            $style_name = $_POST['style'] ?? '';
            list($styles, $styles_dict) = load_styles();
            
            if (!empty($style_name) && isset($styles_dict[$style_name])) {
                $style = $styles_dict[$style_name];
                $image_url = extract_image_url($style['remark']);
                
                echo json_encode([
                    'status' => 'success',
                    'prompt' => $style['prompt'],
                    'remark' => $style['remark'],
                    'image_url' => $image_url
                ]);
            } else {
                echo json_encode([
                    'status' => 'error',
                    'message' => '样式不存在'
                ]);
            }
            exit;
            
        case 'query_key':
            $custom_key = $_POST['api_key'] ?? '';
            $result = query_api_key_usage($custom_key);
            echo json_encode([
                'status' => 'success',
                'result' => $result
            ]);
            exit;
            
        case 'generate_image':
            $prompt = $_POST['prompt'] ?? '';
            $api_key = $_POST['api_key'] ?? '';
            $save_path = $_POST['save_path'] ?? $default_download_path;
            
            // 只获取实际发送的图片数据
            $images = [];
            for ($i = 1; $i <= 3; $i++) {
                $image_key = "image{$i}";
                if (isset($_POST[$image_key]) && !empty($_POST[$image_key])) {
                    $images[] = $_POST[$image_key];
                }
            }
            
            $result = generate_image($prompt, $images, $api_key, $save_path);
            echo json_encode($result);
            exit;
            
        default:
            echo json_encode([
                'status' => 'error',
                'message' => '未知操作'
            ]);
            exit;
    }
}

// 加载样式数据
list($style_names, $styles_dict) = load_styles();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nano Banana V2.1.0</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        // 配置Tailwind自定义颜色和字体
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        primary: '#667eea',
                        secondary: '#764ba2',
                        accent: '#f97316',
                        dark: {
                            100: '#1e293b',
                            200: '#0f172a',
                            300: '#020617'
                        },
                        light: {
                            100: '#f8fafc',
                            200: '#e2e8f0',
                            300: '#cbd5e1'
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.5s ease-in-out',
                        'slide-up': 'slideUp 0.5s ease-out',
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    },
                    keyframes: {
                        fadeIn: {
                            '0%': { opacity: '0' },
                            '100%': { opacity: '1' },
                        },
                        slideUp: {
                            '0%': { transform: 'translateY(20px)', opacity: '0' },
                            '100%': { transform: 'translateY(0)', opacity: '1' },
                        }
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-gradient {
                background-clip: text;
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }
            .card-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }
            .btn-primary {
                @apply bg-gradient-to-r from-primary to-secondary text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 hover:shadow-lg hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-primary/50;
            }
            .btn-secondary {
                @apply bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 font-medium py-2 px-4 rounded-lg transition-all duration-300 hover:shadow-md hover:bg-gray-300 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-400/50;
            }
            .input-field {
                @apply w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-dark-100 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all duration-200;
            }
            .card {
                @apply bg-white dark:bg-dark-100 rounded-xl shadow-md p-6 transition-all duration-300;
            }
            .log-text {
                @apply whitespace-pre-wrap font-mono text-sm;
            }
        }
    </style>
</head>
<body class="bg-gray-50 dark:bg-dark-200 text-gray-800 dark:text-gray-200 min-h-screen transition-colors duration-300">
    <!-- 模式切换按钮 -->
    <button id="theme-toggle" class="fixed top-4 right-4 p-2 rounded-full bg-white dark:bg-dark-100 shadow-md z-50 transition-all duration-300">
        <i class="fa fa-moon-o dark:hidden text-xl"></i>
        <i class="fa fa-sun-o hidden dark:block text-xl text-yellow-400"></i>
    </button>

    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- Hero区域 -->
        <div class="bg-gradient-to-r from-primary to-secondary rounded-2xl p-8 md:p-12 mb-10 text-white shadow-lg animate-fade-in">
            <div class="max-w-3xl mx-auto text-center">
                <h1 class="text-[clamp(2rem,5vw,3.5rem)] font-bold mb-4 leading-tight">
                    🎨 Nano Banana V2.1.0
                </h1>
                <p class="text-[clamp(1rem,2vw,1.25rem)] opacity-90 mb-6">
                    用Nano Banana释放你的想象力！
                </p>
            </div>
        </div>

        <!-- 主要内容区 -->
        <div id="generator" class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-16 animate-slide-up">
            <!-- 左侧：输入区域 -->
            <div class="space-y-6">
                <!-- 样式选择卡片 -->
                <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-paint-brush text-primary mr-2"></i>第一步：选择提示词样式
                    </h3>
                    <div class="flex flex-col sm:flex-row gap-3">
                        <select id="style-select" class="input-field sm:flex-1">
                            <option value="">选择提示词样式示例</option>
                            <?php foreach ($style_names as $style): ?>
                                <option value="<?php echo htmlspecialchars($style); ?>"><?php echo htmlspecialchars($style); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button id="preview-style" class="btn-secondary whitespace-nowrap">
                            <i class="fa fa-eye mr-1"></i>先看示例效果
                        </button>
                    </div>
                </div>

                <!-- 提示词输入卡片 -->
                <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-comment text-primary mr-2"></i>第二步：输入提示词
                    </h3>
                    <textarea id="prompt" rows="8" class="input-field" placeholder="输入修改提示词：默认不输入是手办玩偶的英文提示词">create a 1/7 scale commercialized figure of the character in the illustration, in a realistic style and environment. Place the figure on a computer desk, using a circular transparent acrylic base without any text. On the computer screen, display the ZBrush modeling process of the figure. Next to the computer screen, place a BANDAI-style toy packaging box printed with the original artwork.</textarea>
                </div>

                <!-- 图片上传卡片 -->
                <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-image text-primary mr-2"></i>第三步：输入图片
                    </h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block mb-2 text-sm font-medium">必传图 1：输入第一张图</label>
                            <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:bg-gray-100 dark:hover:bg-dark-300 transition-colors duration-200">
                                <input type="file" id="image1" accept="image/*" class="hidden" onchange="previewImage(event, 'preview1')">
                                <label for="image1" class="cursor-pointer">
                                    <i class="fa fa-upload text-3xl text-gray-400 mb-2"></i>
                                    <p>点击上传图片</p>
                                </label>
                                <div id="preview1" class="mt-3 hidden">
                                    <img src="" alt="预览图" class="max-w-full max-h-48 mx-auto rounded">
                                </div>
                                <div class="mt-3">
                                    <input type="text" id="image-url1" class="input-field" placeholder="或输入图片URL">
                                </div>
                            </div>
                        </div>
                        
                        <!-- 可选图 2：输入第二张图 -->
<div class="space-y-4">
    <div class="flex items-center justify-between">
        <label class="block text-sm font-medium">可选图 2：输入第二张图</label>
        <label class="inline-flex items-center cursor-pointer">
            <input type="checkbox" id="toggle-image2" class="sr-only peer" onchange="toggleImageInput(2)">
            <div class="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
            <span class="ms-3 text-sm font-medium text-gray-900 dark:text-gray-300">启用</span>
        </label>
    </div>
    <div id="image2-container" class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:bg-gray-100 dark:hover:bg-dark-300 transition-colors duration-200">
        <input type="file" id="image2" accept="image/*" class="hidden" onchange="previewImage(event, 'preview2')">
        <label for="image2" class="cursor-pointer">
            <i class="fa fa-upload text-3xl text-gray-400 mb-2"></i>
            <p>点击上传图片</p>
        </label>
        <div id="preview2" class="mt-3 hidden">
            <img src="" alt="预览图" class="max-w-full max-h-48 mx-auto rounded">
        </div>
        <div class="mt-3">
            <input type="text" id="image-url2" class="input-field" placeholder="或输入图片URL">
        </div>
    </div>
</div>

<!-- 可选图 3：输入第三张图 -->
<div class="space-y-4">
    <div class="flex items-center justify-between">
        <label class="block text-sm font-medium">可选图 3：输入第三张图</label>
        <label class="inline-flex items-center cursor-pointer">
            <input type="checkbox" id="toggle-image3" class="sr-only peer" onchange="toggleImageInput(3)">
            <div class="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
            <span class="ms-3 text-sm font-medium text-gray-900 dark:text-gray-300">启用</span>
        </label>
    </div>
    <div id="image3-container" class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:bg-gray-100 dark:hover:bg-dark-300 transition-colors duration-200">
        <input type="file" id="image3" accept="image/*" class="hidden" onchange="previewImage(event, 'preview3')">
        <label for="image3" class="cursor-pointer">
            <i class="fa fa-upload text-3xl text-gray-400 mb-2"></i>
            <p>点击上传图片</p>
        </label>
        <div id="preview3" class="mt-3 hidden">
            <img src="" alt="预览图" class="max-w-full max-h-48 mx-auto rounded">
        </div>
        <div class="mt-3">
            <input type="text" id="image-url3" class="input-field" placeholder="或输入图片URL">
        </div>
    </div>
</div>

                    </div>
                </div>
            </div>

            <!-- 右侧：输出和控制区域 -->
            <div class="space-y-6">
                <!-- API Key和查询卡片 -->
                <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-key text-primary mr-2"></i>API Key
                    </h3>
                    <div class="flex flex-col sm:flex-row gap-3 mb-3">
                        <input type="password" id="api-key" class="input-field sm:flex-1" placeholder="输入API Key（优先级：自定义输入KEY）">
                        <button id="query-key" class="btn-secondary whitespace-nowrap">
                            <i class="fa fa-search mr-1"></i>查询使用情况
                        </button>
                    </div>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        申请地址：<a href="https://openrouter.ai/" target="_blank" class="text-primary hover:underline">https://openrouter.ai/</a>，邮箱免费注册，免费申请一个API Key再输入。
                    </p>
                </div>

                <!-- 保存路径卡片 -->
                <!-- <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-folder-open text-primary mr-2"></i>保存路径
                    </h3>
                    <input type="text" id="save-path" class="input-field" value="<?php echo htmlspecialchars($default_download_path); ?>">
                </div> -->


                <!-- 日志卡片 -->
                <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-terminal text-primary mr-2"></i>响应日志
                    </h3>
                    <div id="log-detail" class="min-h-[100px] p-4 bg-gray-100 dark:bg-dark-300 rounded-lg text-sm overflow-auto log-text">
                        等待操作...
                    </div>
                </div>

                
                <!-- 生成按钮 -->
                <div class="card card-hover">
                    <button id="generate-btn" class="w-full btn-primary text-lg py-3">
                        <i class="fa fa-cog mr-2"></i>第四步：生成图片
                    </button>
                </div>

                <!-- 输出图片卡片 -->
                <div class="card card-hover">
                    <h3 class="text-xl font-semibold mb-4 flex items-center">
                        <i class="fa fa-picture-o text-primary mr-2"></i>生成的图片
                    </h3>
                    <div id="output-image-container" class="border-2 border-gray-300 dark:border-gray-600 rounded-lg p-4 text-center bg-gray-100 dark:bg-dark-300 min-h-[300px] flex flex-col items-center justify-center">
                        <div id="loading-indicator" class="hidden">
                            <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                            <p>正在生成图片，请稍候...</p>
                        </div>
                        <div id="output-placeholder">
                            <i class="fa fa-image text-5xl text-gray-400 mb-3"></i>
                            <p>生成的图片将显示在这里</p>
                        </div>
                        <div id="output-image" class="hidden w-full">
                            <img src="" alt="生成的图片" class="max-w-full max-h-[1000px] mx-auto rounded-lg cursor-pointer" id="result-image">
                            <button id="download-image" class="mt-4 btn-secondary">
                                <i class="fa fa-download mr-1"></i>下载图片
                            </button>
                        </div>
                    </div>
                </div>


            </div>
        </div>

        <!-- 页脚 -->
        <footer class="text-center py-6 border-t border-gray-200 dark:border-gray-700 animate-fade-in">
            <p class="text-gray-600 dark:text-gray-400">
                &copy; <?php echo date('Y'); ?> Nano Banana V2.1.0 | Design By BOZOYAN
            </p>
        </footer>
    </div>

    <script>
        // 深色模式切换
        const themeToggle = document.getElementById('theme-toggle');
        const html = document.documentElement;
        
        // 检查系统偏好
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            html.classList.add('dark');
        }
        
        themeToggle.addEventListener('click', () => {
            html.classList.toggle('dark');
        });

        // 页面加载时从cookie恢复API Key
        document.addEventListener('DOMContentLoaded', function() {
            const savedApiKey = getCookie('openrouter_api_key');
            if (savedApiKey) {
                document.getElementById('api-key').value = savedApiKey;
            }
        });

        // 图片预览
        function previewImage(event, previewId) {
            const file = event.target.files[0];
            if (!file) return;
            
            const previewContainer = document.getElementById(previewId);
            const previewImg = previewContainer.querySelector('img');
            
            const reader = new FileReader();
            reader.onload = function(e) {
                previewImg.src = e.target.result;
                previewContainer.classList.remove('hidden');
            }
            reader.readAsDataURL(file);
        }

        // 样式预览
        document.getElementById('preview-style').addEventListener('click', async () => {
            const styleSelect = document.getElementById('style-select');
            const selectedStyle = styleSelect.value;
            const promptTextarea = document.getElementById('prompt');
            const logDetail = document.getElementById('log-detail');
            const outputImage = document.getElementById('output-image');
            const outputPlaceholder = document.getElementById('output-placeholder');
            const outputImg = document.getElementById('result-image');
            
            if (!selectedStyle) {
                logDetail.textContent = '请先选择一个样式';
                return;
            }
            
            try {
                logDetail.textContent = '正在加载样式预览...';
                
                const response = await fetch('', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        'action': 'preview_style',
                        'style': selectedStyle
                    })
                });
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    promptTextarea.value = result.prompt;
                    
                    // 显示样式参数到日志区域，只显示中文描述部分
                    let logContent = "=== 样式参数 ===\n";
                    logContent += "样式名称: " + selectedStyle + "\n";
                    logContent += "提示词: " + result.prompt + "\n";
                    
                    // 从remark中提取中文描述部分（去除URL）
                    if (result.remark) {
                        // 使用正则表达式移除URL部分，只保留中文描述
                        const urlRegex = /https?:\/\/[^\s]+/g;
                        let chineseDesc = result.remark.replace(urlRegex, '').trim();
                        // 去除可能的多余标点符号
                        chineseDesc = chineseDesc.replace(/^[，,。.；;：:]+/, '').replace(/[，,。.；;：:]+$/, '').trim();
                        logContent += "备注: " + (chineseDesc || '无') + "\n";
                    } else {
                        logContent += "备注: 无\n";
                    }
                    
                    logDetail.textContent = logContent;
                    
                    // 显示URL图片到生成的图片区域
                    if (result.image_url) {
                        outputPlaceholder.classList.add('hidden');
                        outputImage.classList.remove('hidden');
                        outputImg.src = result.image_url;
                        outputImg.alt = selectedStyle + ' 预览图';
                        
                        // 绑定图片点击下载事件
                        outputImg.onclick = function() {
                            downloadImage(result.image_url, selectedStyle + '_preview.png');
                        };
                    } else {
                        // 如果没有预览图，恢复显示占位符
                        outputImage.classList.add('hidden');
                        outputPlaceholder.classList.remove('hidden');
                    }
                } else {
                    logDetail.textContent = '错误: ' + (result.message || '无法加载样式预览');
                }
            } catch (error) {
                logDetail.textContent = '加载样式失败: ' + error.message;
            }
        });

        // 生成图片按钮事件
document.getElementById('generate-btn').addEventListener('click', async () => {
    const prompt = document.getElementById('prompt').value;
    const apiKey = document.getElementById('api-key').value;
    const logDetail = document.getElementById('log-detail');
    const loadingIndicator = document.getElementById('loading-indicator');
    const outputPlaceholder = document.getElementById('output-placeholder');
    const outputImage = document.getElementById('output-image');
    const outputImg = document.getElementById('result-image');

    // 保存API Key到cookie
    if (apiKey) {
        setCookie('openrouter_api_key', apiKey, 365);
    }

    // 获取图片数据（严格验证）
    // 必传图1：必须存在
    let image1 = document.getElementById('preview1').querySelector('img')?.src;
    if (!image1) {
        image1 = document.getElementById('image-url1').value.trim();
        if (!image1) {
            logDetail.textContent = '请上传第一张图片或输入有效的图片URL（至少需要一张图片）';
            return;
        }
        // 验证URL格式
        try {
            new URL(image1);
        } catch (e) {
            logDetail.textContent = '第一张图片的URL格式无效';
            return;
        }
    }

    // 可选图2：仅在开关开启时处理
    let image2 = null;
    if (document.getElementById('toggle-image2').checked) {
        image2 = document.getElementById('preview2').querySelector('img')?.src;
        if (!image2) {
            image2 = document.getElementById('image-url2').value.trim();
            if (image2) {
                // 验证URL格式
                try {
                    new URL(image2);
                } catch (e) {
                    logDetail.textContent = '第二张图片的URL格式无效';
                    return;
                }
            }
        }
    }

    // 可选图3：仅在开关开启时处理
    let image3 = null;
    if (document.getElementById('toggle-image3').checked) {
        image3 = document.getElementById('preview3').querySelector('img')?.src;
        if (!image3) {
            image3 = document.getElementById('image-url3').value.trim();
            if (image3) {
                // 验证URL格式
                try {
                    new URL(image3);
                } catch (e) {
                    logDetail.textContent = '第三张图片的URL格式无效';
                    return;
                }
            }
        }
    }

    // 构建图片数组并过滤空值
    const images = [image1, image2, image3].filter(img => img); // 过滤掉空值

    // 再次验证：确保至少有一张有效图片（理论上image1已经验证过，但双重保险）
    if (images.length === 0) {
        logDetail.textContent = '未能获取到任何有效的图片数据';
        return;
    }

    try {
        logDetail.textContent = '开始生成图片...';
        loadingIndicator.classList.remove('hidden');
        outputPlaceholder.classList.add('hidden');
        outputImage.classList.add('hidden');

        // 准备表单数据
        const formData = new URLSearchParams();
        formData.append('action', 'generate_image');
        formData.append('prompt', prompt);
        formData.append('api_key', apiKey);

        // 添加非空图片（最多3张）
        images.forEach((img, index) => {
            formData.append(`image${index + 1}`, img);
        });

        const response = await fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: formData
        });

        const result = await response.json();
        loadingIndicator.classList.add('hidden');

        if (result.success && result.image) {
            logDetail.textContent = result.log;
            outputPlaceholder.classList.add('hidden');
            outputImage.classList.remove('hidden');
            outputImg.src = result.image;
            outputImg.alt = '生成的图片';
            // 绑定图片点击下载事件
            outputImg.onclick = function() {
                downloadImage(result.image, 'generated_image.png');
            };
        } else {
            logDetail.textContent = result.log || '生成图片失败';
            outputPlaceholder.classList.remove('hidden');
            outputImage.classList.add('hidden');
        }
    } catch (error) {
        loadingIndicator.classList.add('hidden');
        logDetail.textContent = '生成图片失败: ' + error.message;
        outputPlaceholder.classList.remove('hidden');
        outputImage.classList.add('hidden');
    }
});
        

        // 查询API Key按钮事件
        document.getElementById('query-key').addEventListener('click', async () => {
            const apiKey = document.getElementById('api-key').value;
            const logDetail = document.getElementById('log-detail');
            
            // 保存API Key到cookie
            if (apiKey) {
                setCookie('openrouter_api_key', apiKey, 365);
            }
            
            try {
                logDetail.textContent = '查询API Key使用情况...';
                
                const response = await fetch('', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        'action': 'query_key',
                        'api_key': apiKey
                    })
                });
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    logDetail.textContent = result.result;
                } else {
                    logDetail.textContent = '查询失败: ' + (result.message || '未知错误');
                }
            } catch (error) {
                logDetail.textContent = '查询API Key失败: ' + error.message;
            }
        });

        // 下载图片按钮事件
        document.getElementById('download-image').addEventListener('click', function() {
            const outputImg = document.getElementById('result-image');
            if (outputImg.src) {
                // 获取图片名称，默认为generated_image.png
                let fileName = 'generated_image.png';
                const styleSelect = document.getElementById('style-select');
                if (styleSelect.value) {
                    fileName = styleSelect.value + '_generated.png';
                }
                downloadImage(outputImg.src, fileName);
            }
        });

        // 图片下载工具函数
        function downloadImage(url, filename) {
            try {
                // 处理base64图片或网络图片
                if (url.startsWith('data:')) {
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                } else {
                    // 网络图片需要先转为blob
                    fetch(url)
                        .then(response => {
                            if (!response.ok) throw new Error('图片下载失败');
                            return response.blob();
                        })
                        .then(blob => {
                            const blobUrl = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = blobUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            URL.revokeObjectURL(blobUrl);
                        })
                        .catch(error => {
                            alert('下载失败: ' + error.message);
                        });
                }
            } catch (error) {
                alert('下载失败: ' + error.message);
            }
        }

        // 控制可选图片输入区域的开关
function toggleImageInput(imageNum) {
    const container = document.getElementById(`image${imageNum}-container`);
    const toggle = document.getElementById(`toggle-image${imageNum}`);
    if (toggle.checked) {
        container.classList.remove('opacity-50', 'pointer-events-none');
    } else {
        container.classList.add('opacity-50', 'pointer-events-none');
    }
}

// 页面加载时，默认禁用可选图2和3
document.addEventListener('DOMContentLoaded', function() {
    // ... (原有的cookie恢复代码)

    // 默认禁用可选图2和3的容器
    document.getElementById('image2-container').classList.add('opacity-50', 'pointer-events-none');
    document.getElementById('image3-container').classList.add('opacity-50', 'pointer-events-none');
});

        // Cookie工具函数
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }

        function setCookie(name, value, days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            const expires = `expires=${date.toUTCString()}`;
            document.cookie = `${name}=${value}; ${expires}; path=/`;
        }
    </script>
</body>
</html>
